package com.liholin.springboot.sample.utils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Created by Andon on 2017/8/7.
 */
public class EncryptionUtil {
    /**
     * 加密算法
     *
     * @param passwordConstSalt 常量--每个版本对应自己的值（
     * @param password          密码
     * @return
     * @throws NoSuchAlgorithmException
     * @throws UnsupportedEncodingException
     */
    public static String Encode(String passwordConstSalt, String password) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        String result = "";
        result = getSha1(EncoderByMd5(passwordConstSalt + password) + password);
        return result;
    }

    private static String EncoderByMd5(String str) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        MessageDigest messageDigest = MessageDigest.getInstance("MD5");
        messageDigest.update((str).getBytes("UTF-8"));
        byte b[] = messageDigest.digest();
        int i;
        StringBuffer buffer = new StringBuffer("");
        for (int offset = 0; offset < b.length; offset++) {
            i = b[offset];
            if (i < 0) {
                i += 256;
            }
            if (i < 16) {
                buffer.append("0");
            }
            buffer.append(Integer.toHexString(i));
        }
        return buffer.toString();
    }

    private static String getSha1(String str) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        if (null == str || 0 == str.length()) {
            return null;
        }
        char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                'a', 'b', 'c', 'd', 'e', 'f'};
        MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
        mdTemp.update(str.getBytes("UTF-8"));

        byte[] md = mdTemp.digest();
        int j = md.length;
        char[] buf = new char[j * 2];
        int k = 0;
        for (int i = 0; i < j; i++) {
            byte byte0 = md[i];
            buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
            buf[k++] = hexDigits[byte0 & 0xf];
        }
        return new String(buf);
    }
}
